// Copyright Leonid Shlyapnikov 2010
// Distributed under the GNU Lesser General Public License http://www.gnu.org/licenses/lgpl.html
//    author: Leonid Shlyapnikov, created on: Feb 13, 2010

#include "./String.h"

#include <string>

#include "./MemoryArea.h"
//#include "./knr2.h"

namespace fixparser {

String::String(MemoryArea* const memoryArea):
        str_(0), length_(0), memoryArea_(memoryArea)
{
}

String::~String() {
}

inline
void
String::copy_in(const char* new_str, size_t new_length) {
    // always allocate for a new_str
    char* buffer = memoryArea_->allocate<char>(new_length + 1);  // + 1 for terminating zero

    std::strncpy(buffer, new_str, new_length);
    buffer[new_length] = '\0';

    this->set(buffer, new_length);
}

void
String::copy_in(const String& that) {
    this->copy_in(that.str_, that.length_);
}

inline
void
String::set(const char* new_str, size_t new_length) {
    this->str_ = new_str;
    this->length_ = new_length;
}

inline
String&
String::assign(const char* new_str, size_t new_length) {
    if (memoryArea_->contains(new_str)) {
        this->set(new_str, new_length);
    } else {
        this->copy_in(new_str, new_length);
    }

    return *this;
}

String&
String::assign(const char* str)  {
    return this->assign(str, std::strlen(str));
}

String&
String::assign(const String& that) {
    return this->assign(that.str_, that.length_);
}

String&
String::assign(const std::string& that) {
    return this->assign(that.c_str(), that.size());
}

}
